import axios from 'axios'
import { initConfigHeader, initConfigData, handlerResponse, handlerError, initConfigAuth } from './interceptors'
import microServices from './microServices'

const service = axios.create({
    baseURL: process.env.VUE_APP_REQUEST_BASE_URL,
    timeout: 10 * 1000, // 请求超时时间10s
    microService: 'default' // 自定义字段-微服务配置名
})

// request拦截器
service.interceptors.request.use(
    config => {
        // 获取对应的微服务配置
        config = {
            ...config,
            ...microServices[config.microService]
        }
        config = initConfigHeader(config)
        config = initConfigAuth(config)
        config = initConfigData(config)
        return config
    },
    error => {
        console.log(error) // for debug
        Promise.reject(error)
    }
)

// response拦截器
service.interceptors.response.use(
    res => handlerResponse(res, microServices[res.config.microService].responseAlias),
    handlerError
)

export default service